/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rw.table;

import com.rw.table.editor.ICellEditor;
import com.rw.table.formatter.ICellFormatter;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;

/**
 *
 * @author Rene Tapia
 */
public class TableEditor extends AbstractCellEditor implements TableCellEditor {

    private EditionStyle style;
    private ICellEditor actualEditor;
    private ICellFormatter actualFormatter;

    public TableEditor() {
        this(EditionStyle.INSTANT_ACCESS_STYLE);
    }

    public TableEditor(EditionStyle style) {
        this.style = style;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        TableModel model = table.getModel();
        if (model instanceof ATableModel) {
            ATableModel tableModel = (ATableModel) model;
            this.actualEditor = tableModel.getEditor(row, column);
            this.actualFormatter = tableModel.getFormatter(row, column);
            Color color = tableModel.getBackground(row, column);
            TableInfo info = new TableInfo(table, value, isSelected, true, row, column, actualFormatter, color);
            return actualEditor.getComponent(info);
        } else {
            throw new RuntimeException("El modelo no es instancia de 'ATableModel'");
        }
    }

    @Override
    public boolean isCellEditable(EventObject e) {
        if (style == EditionStyle.EXCEL_STYLE) {
            if (e instanceof MouseEvent) {
                return ((MouseEvent) e).getClickCount() == 2;
            }
        }
        return true;
    }

    @Override
    public Object getCellEditorValue() {
        return actualEditor.getCellEditorValue(actualFormatter);
    }
}
